var json_bookget = [];
var userid = sessionStorage.getItem('user');
let mylikebookf1 = localStorage.getItem('mylikebook');
let likebooks = JSON.parse(mylikebookf1);
if(!likebooks){
    likebooks = {
        booksList: []
    };
}
document.addEventListener('DOMContentLoaded', function() {
    yhload.show();
    fetch('/book/searchall.php')
    .then(response => response.json())
    .then(data => {
        let likebooks = mylikebookf1 ? JSON.parse(mylikebookf1) : { booksList: [] };
        data.forEach(function(novel) {
            const bookItem = document.createElement('div');
            bookItem.className = 'book-item';
            let isLiked = likebooks.booksList.some(item => item.book === novel.name && item.user === userid);
            let likeIcon = isLiked ? '<span class="liked-icon">(已收藏)</span>' : '';
            bookItem.innerHTML = `
                <a href="/novelread.php?read=${novel.name}">
                    <img src="${novel.img}" alt="${novel.name}">
                    <h3>${novel.name}${likeIcon}</h3>
                    <p style='display:none;'>${novel.name}</p>
                    <p2 style='display:none;'>${novel.fromer}</p2>
                </a>
            `;
            bookItem.addEventListener('contextmenu', showMenu);
            document.querySelector('.book-grid').appendChild(bookItem);
        });
        yhload.hide();
    });
});

function searchBooks() {
    const inputbook = document.getElementById('searchInput').value;
    fetch('book/searchbook.php?book='+inputbook)
        .then(response => response.json())
        .then(data => {
            if(data.msg === 404){
                Qmsg.error('没有找到此书籍');
                return;
            }
            Qmsg.success('搜索到以下相关条件的书籍');
            document.querySelector('.book-grid').innerHTML = '';
        let likebooks = mylikebookf1 ? JSON.parse(mylikebookf1) : { booksList: [] };
            data.forEach(function(novel) {
                const bookItem = document.createElement('div');
            bookItem.className = 'book-item';
            let isLiked = likebooks.booksList.some(item => item.book === novel.name && item.user === userid);
            let likeIcon = isLiked ? '<span class="liked-icon">(已收藏)</span>' : '';
            bookItem.innerHTML = `
                <a href="/novelread.php?read=${novel.name}">
                    <img src="${novel.img}" alt="${novel.name}">
                    <h3>${novel.name}${likeIcon}</h3>
                    <p style='display:none;'>${novel.name}</p>
                    <p2 style='display:none;'>${novel.fromer}</p2>
                </a>
            `;
            bookItem.addEventListener('contextmenu', showMenu);
            document.querySelector('.book-grid').appendChild(bookItem);
            });
        });
}
function false_likebook(book) {
    let isLiked = likebooks.booksList.some(item => item.book === book);
    return isLiked; 
}
function delmylikebook(bookName) {
    likebooks.booksList = likebooks.booksList.filter(function(book) {
        return book.book !== bookName;
    });
    console.log(bookName);
    localStorage.setItem('mylikebook', JSON.stringify(likebooks));
    Qmsg.success('取消收藏成功');
}
function showMenu(env){
	    	env.preventDefault();	    	
	        var e = env || window.event;
	       var context = document.getElementById("context");
           json_bookget = [
            this.querySelector('p').innerText,
            this.querySelector('img').src,
            this.querySelector('p2').innerText
            ];   
            var isLiked = false_likebook(json_bookget[0]);
    if (isLiked) {
        document.getElementById("likewb").innerText = '取消收藏';
        document.getElementById("likewb").onclick = function() {
            delmylikebook(json_bookget[0]); 
        };
    } else {
        document.getElementById("likewb").innerText = '收藏此书';
        document.getElementById("likewb").onclick = function() {
            lovethisbook();
        };
    }                
	       context.style.display = "block";
	       var x = e.clientX;
	       var y = e.clientY;
	       context.style.left =x-100+"px" 
	       context.style.top = y+"px" 
	       return false;
	    };
	  document.onclick = function(){
		  closeMenu()
	  };
	  function closeMenu(){
			var contextmenu = document.getElementById("context");
		      contextmenu.style.display = "none";
	}
    function addBook(newbook) {
        likebooks.booksList.push(newbook)
        localStorage.setItem('mylikebook', JSON.stringify(likebooks)); 
    }
    function lovethisbook(){
        if(userid === null){
            Qmsg.error('请先登录');
            return;
        }
        addBook({ user: userid, book: json_bookget[0], img: json_bookget[1] });
        Qmsg.success(json_bookget[0]+'收藏成功');
    }
    function giveidea(){
        if(userid === null){
            Qmsg.error('请先登录');
            return;
        }
        layui.use(['element'], function(){
            var element = layui.element;
            layer.open({
                type: 2,
                title: '精言细语胜于千言万语',
                shadeClose: true,
                shade: 0.8,
                area: ['580px', '60%'],
                shadeClose: false,
                content: 'ideaer.php?book='+json_bookget[0]+'&fromer='+json_bookget[2] 
            });   
        });
        }